package cn.edu.klmy.controller;

import cn.edu.klmy.dao.ICatalogDao;
import cn.edu.klmy.dao.IParamDao;
import cn.edu.klmy.models.menu.Catalog;
import cn.edu.klmy.models.menu.Node;
import cn.edu.klmy.models.param.SystemParam;
import cn.edu.klmy.spring.security.core.userdetails.CourseSystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 页面控制
 *
 * @author 顾伟
 *         创建日期：13-2-3
 */
@Controller
public class WebPageController {
    @Autowired
    private ICatalogDao catalogDao;

    @Autowired
    private IParamDao paramDao;

    /**
     * 系统初始登录页面
     *
     * @return 登录界面
     */
    @RequestMapping("/index")
    public String loginPage(Model model){
        model.addAttribute("loginFailure", false);
        return "login";
    }

    /**
     * 系统主界面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String loadCatalogs(HttpServletRequest request,Model model) throws ParseException {
        //加载选课参数
        SystemParam systemParam = paramDao.getCurrentParam();
        HttpSession session = request.getSession();
        session.setAttribute("param",systemParam);

        //加载用户目录树
        Iterator grantedAuthorityIterator = SecurityContextHolder.getContext().getAuthentication().getAuthorities().iterator();
        List<Catalog> catalogList = new ArrayList<Catalog>();
        while (grantedAuthorityIterator.hasNext()) {
            GrantedAuthority grantedAuthority = (GrantedAuthority) grantedAuthorityIterator.next();
            String roleId = grantedAuthority.getAuthority();
            long currentTime = System.currentTimeMillis();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = df.parse(systemParam.getElectiveStart());
            Date endDate = df.parse(systemParam.getElectiveEnd());
            List<Catalog> catalogsRole = null;
            if (currentTime >= startDate.getTime() && currentTime <= endDate.getTime()) {
                catalogsRole = catalogDao.getCatalogByRole(Integer.parseInt(roleId),true);
            }else{
                catalogsRole = catalogDao.getCatalogByRole(Integer.parseInt(roleId),false);
            }
            for (Catalog catalog : catalogsRole) {
                boolean isContain = false;
                for (Catalog catalogReturn : catalogList) {
                    if (catalog.getMenuId() == catalogReturn.getMenuId()) {
                        isContain = true;
                    }
                }
                if (!isContain) {
                    catalogList.add(catalog);
                }
            }
        }


        model.addAttribute("Catalogs", catalogList);



        return "main";
    }

    /**
     * 登录失败界面
     *
     * @param model
     * @return
     */
    @RequestMapping("/login/failure")
    public String loginError(Model model) {
        model.addAttribute("loginFailure", true);
        return "login";
    }

    @RequestMapping("/student")
    public String studentManagementPage() {
        return "studentManage";
    }

    @RequestMapping("/teacher")
    public String teacherManagementPage() {
        return "teacherManage";
    }

    @RequestMapping("/clasz")
    public String claszManagementPage() {
        return "claszManage";
    }

    @RequestMapping("/schedule")
    public String scheduleManagementPage() {
        return "schedule_manage";
    }

    @RequestMapping("/classroom")
    public String classroomManagementPage() {
        return "classroomManage";
    }

    @RequestMapping("/structure")
    public String structureManagementPage() {
        return "courseStructureManage";
    }

    @RequestMapping("/course")
    public String courseManagementPage() {
        return "courseManage";
    }

    @RequestMapping("/textbook")
    public String textbookManagementPage() {
        return "textbookManage";
    }

    /**
     * @return 角色管理界面
     */
    @RequestMapping("/personal")
    public String roleManagementPage() {
        return "personal";
    }

//    @RequestMapping("/param")
//    public String paramManagementPage() {
//        return "param_manage";
//    }

    @RequestMapping("/electiveTable")
    public String electiveTablePage(HttpServletRequest request,Model model) throws Exception{
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        long currentTime = System.currentTimeMillis();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = df.parse(systemParam.getElectiveStart());
        Date endDate = df.parse(systemParam.getElectiveEnd());
        if (currentTime >= startDate.getTime() && currentTime <= endDate.getTime()) {
            model.addAttribute("isElective",true);
        }else{
            model.addAttribute("isElective",false);
        }
        return "electiveTable";
    }

    @RequestMapping("/electiveSituation")
    public String electiveSituationPage(){
        return "electiveSituation";
    }

    @RequestMapping("/attendanceSituation")
    public String attendanceSituationPage(){
        return "attendanceSituation";
    }

    @RequestMapping("/courseStudyManage")
    public String courseStudyManagePage(HttpServletRequest request,Model model) throws Exception{
        HttpSession session = request.getSession();
        SystemParam systemParam = (SystemParam) session.getAttribute("param");
        long currentTime = System.currentTimeMillis();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = df.parse(systemParam.getElectiveStart());
        Date endDate = df.parse(systemParam.getElectiveEnd());
        if (currentTime >= startDate.getTime() && currentTime <= endDate.getTime()) {
            model.addAttribute("isElective",true);
        }else{
            model.addAttribute("isElective",false);
        }
        return "courseStudyManage";
    }

    @RequestMapping("/session/invalid")
    public String invalidSessionPage(Model model) {
        model.addAttribute("loginFailure", false);
        return "index";
    }

    @RequestMapping("/session/expired")
    public String expiredSessionPage(Model model)throws Exception{
        model.addAttribute("loginFailure", false);
        return "index";
    }
}
